#include "CameraAgent.h"

using namespace std;

bool CameraAgent::isTakingPicture = false;

//Constructor
CameraAgent::CameraAgent(std::string name) 
	: Agent(name)
{
	state = None;
}

CameraAgent::~CameraAgent()
{
	
}

//Messages

//From Nest
void CameraAgent::msgIThinkImFull(PartType partType) 
{
	p = Stable;
	for ( int i = 0; i < nests.size(); ++i )
	{
		NestAgent* nest = nests.at( i );
		if (nest->getGUI()->NumberOfParts != 9) //little hacks.
		{
			if (p != BadNest)
			{
				p = Unstable;
			}
			break;
		}
		else
		{
			// Check if parts in nest match the PartType that they are supposed to be
			for (int k = 0; k < 3; k++)
			{
				for (int j = 0; j < 3; j++)
				{
					if (nest->getGUI()->PartsInNest[k][j]->partType != nest->partType)
					{
						p = BadNest;
					}
				}
			}
		}
	}

	/*if (this->isBroken) 
	{
		p = Stable;
	}*/
	state = TakingPicture;
	stateChanged();
}

bool CameraAgent::pickAndExecuteAnAction() 
{
	if(state == TakingPicture) 
	{ 
		takePicture();
		return true;
	}

	return false;
}

void CameraAgent::takePicture()
{
	tellGUIToTakePicture();
	CameraAgent::isTakingPicture = true;
	givePictureToNest();
	CameraAgent::isTakingPicture = false;
	state = None;
}

//To Nest
void CameraAgent::givePictureToNest() 
{
	for (int i = 0; i < nests.size(); ++i )
	{
		nests.at( i )->msgHereIsAPicture(p);
	}
	p = NonePicture;
}

//To GUI
void CameraAgent::tellGUIToTakePicture() 
{
	if ( CameraAgent::isTakingPicture == false )
	{
		guiCamera->takePicture();
		
	}
}

std::string CameraAgent::toString() const
{
	return "Camera Agent " + getName();
}

//Setters
void CameraAgent::setNest(NestAgent* n)
{
	nests.push_back(n);
}

void CameraAgent::setGUI(GUICamera* gcam)
{
	guiCamera = gcam;
}

void CameraAgent::handleBreak()
{
	((GUICamera*)guiCamera)->DoBreak();
	/*while ( this->breakSemaphore.getValue() < 1 )
	{
		CameraAgent::pickAndExecuteAnAction();
	}*/
}

void CameraAgent::handleFix()
{
	((GUICamera*)guiCamera)->DoFix();
}